package com.ydd.controller.common;

import com.ydd.result.Result;
import com.ydd.vo.FileVO;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @PostMapping("/upload")
    public Result upload(String type, MultipartFile file) throws IOException {

        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String path = "E:/Code/YDD/nginx-front/html/dist/apiupload/"+type+"/"+date;
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
        File file1 = new File(path);
        file1.mkdirs();

        //copy(file, path);
        InputStream in = file.getInputStream();
        String name = UUID.randomUUID() + "." + suffix;
        String outPath = path+"/"+name;
        OutputStream out = new FileOutputStream(outPath,false);
        byte[] buffer = new byte[1024]; // 1KB.
        // 从字节输入流中读取字节数据，写出去到字节输出流中。读多少写出去多少。
        int len; // 记住每次读取了多少个字节。
        while ((len = in.read(buffer)) != -1){
            out.write(buffer, 0, len);
        }
        out.close();
        in.close();
        
        return Result.success(new FileVO(
                type+"/"+suffix,
                file.getOriginalFilename(),
                "upload/"+type+"/"+date+"/"+name,
                String.valueOf(file.getSize())
        ));
    }
}